package worklog.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import worklog.db.EntryDB;
import worklog.dto.DayDTO;
import worklog.dto.ResponseDTO;

@WebServlet("/day")
public class Day extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private EntryDB entryDB;
	private ResponseDTO responder = new ResponseDTO();
	
    public Day() throws Exception{ super(); }
    
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
		//doGet(request, response); 
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
		entryDB = new EntryDB();
		PrintWriter out = response.getWriter();
		response.setContentType("application/json");
    	if (entryDB.isReady()) out.print(processRequest(request));
    	else out.print(responder.showError("DB connection error"));
    	entryDB.close();
    	out.close();
	}
	
	private String processRequest(HttpServletRequest request){
		HttpSession session = request.getSession();
		if (session.getAttribute("logged") == null || (Boolean)session.getAttribute("logged") != true) return responder.showAuthError();
		int userId = (Integer) session.getAttribute("userId");

    	String date = request.getParameter("date");
        
    	if (date == null || date.length() <= 1) return responder.showError("Incorrect parameters");
    	else {
    		DayDTO day = new DayDTO();
    		
    		try {
				day = entryDB.getDay(userId, date);
			} 
    		catch (SQLException e) {}
    		
    		if (day != null) return day.toString();
    		else return responder.showError("No entries found");
    	}
	}
}